package fr.tocchisu.grepolis.requests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fr.tocchisu.grepolis.model.City;

public class FarmerRequest extends AbstractHTTPRequest {
	private City city;

	private int farmedResourcesPerType;

	public FarmerRequest(City city) {
		this.city = city;
	}

	protected void displayResponseBody() throws IOException {
		String line;
		BufferedReader s = new BufferedReader(new InputStreamReader(server.getInputStream()));
		line = s.readLine();
		String message = city.getTown().getName() + "-" + city.getId();
		while (line != null) {
			if (line.startsWith("{")) {
				String regex = "^.+\"claimed_resources_per_resource_type\":(\\d+).+\"wood\":(\\d+),\"stone\":(\\d+),\"iron\":(\\d+).+$";
				Matcher matcher = Pattern.compile(regex).matcher(line);
				if (matcher.matches()) {
					Integer claimeResourcePerType = Integer.parseInt(matcher.group(1));
					Integer wood = Integer.parseInt(matcher.group(2));
					Integer stone = Integer.parseInt(matcher.group(3));
					Integer iron = Integer.parseInt(matcher.group(4));
					message += " new values : " + wood + "/" + stone + "/" + iron;
					farmedResourcesPerType += claimeResourcePerType;
				} else if (line.contains("start?nosession")) {
					System.out.println("Invalid session");
					System.exit(0);
				} else {
					message += " " + line;
				}
			} else if (line.startsWith("_srvtime")) {
				Date svrTime = new Date(Long.parseLong(line.substring(8)) * 1000);
				message = svrTime + " : " + message;
			} else {
			}
			line = s.readLine();
		}
		System.out.println(message);
		s.close();
	}

	protected String getPostDatas() {
		return "json=%7B%22target_id%22%3A%22" + city.getId()
				+ "%22%2C%22claim_type%22%3A%22normal%22%2C%22time%22%3A300%2C%22town_id%22%3A%22" + city.getTown().getId()
				+ "%22%2C%22nlreq_id%22%3A19070975%7D";
	}

	protected String getURL() {
		return "farm_town_info?action=claim_load&town_id=" + city.getTown().getId() + "&h=" + H;
	}

	@Override
	protected void displayResponse() throws Exception {
		displayResponseBody();
	}
}